﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using TextMining.Helper;
using System.IO;
using System.Web.UI.WebControls;
using Microsoft.Office.Interop.Word;

namespace TextMining
{
    /// <summary>
    /// Summary description for FileHandler
    /// </summary>
    public class FileHandler : IHttpHandler
    {

       

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }

        
    

        public void ProcessRequest(HttpContext context)
        {
            bool isInsert = false; ;
            try
            {
                string strExtension = Path.GetExtension(context.Request.Files[0].FileName).ToLower();
                string sName = RandomString(10);

                HttpPostedFile file = context.Request.Files["Filedata"];
                if (file.ContentLength > 0)
                {
                    string targetDirectory = context.Server.MapPath(context.Request["folder"]);
                    sName = RandomString(10);
                    string targetFilePath = Path.Combine(targetDirectory, sName + strExtension);
                    file.SaveAs(targetFilePath);

                    string sContent = ReadFile(targetFilePath, strExtension);

                    context.Response.ContentType = "text/plain";
                    context.Response.Write(sContent);
                }
                else
                    Logger.FrameworkLogger.Error("Can not upload file (FileHandler.ashx line 27) " + sName);                

                string sFileName = HttpContext.Current.Request.Form["name"];
               

                //Insert into Database

               
            }
            catch (Exception ex)
            {
                Logger.FrameworkLogger.Error("Insert images ",ex);
            }

           
        }

        private string RandomString(int size)
        {
            StringBuilder builder = new StringBuilder();
            Random random = new Random();
            char ch;
            for (int i = 0; i < size; i++)
            {
                ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }

            return builder.ToString();
        }

        public string ReadFile(string filePath, string strExtension)
        {
            StringBuilder sb = new StringBuilder();

            try
            {
                if (!string.IsNullOrEmpty(filePath))
                {
                    if (string.Equals(strExtension, ".txt") == true)  // TXT file
                    {
                        try
                        {
                            using (StreamReader sr = new StreamReader(filePath))
                            {
                                String line = sr.ReadToEnd();
                                sb.Append(line);
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.FrameworkLogger.Error("Read file " + ex.ToString());
                        }

                    }
                    else   // Microsoft word
                    {
                        object fileName = filePath;
                        object readOnly = true;
                        object isVisible = true;
                        object missing = System.Reflection.Missing.Value;
                        Microsoft.Office.Interop.Word.Application oWordApp = new Microsoft.Office.Interop.Word.Application();
                        Microsoft.Office.Interop.Word.Document oWordDoc = new Document();
                        try
                        {
                            oWordApp.Visible = false;
                            oWordDoc = oWordApp.Documents.Open(ref fileName,
                                              ref missing, ref readOnly,
                                              ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref missing,
                                              ref missing, ref missing, ref isVisible,
                                              ref missing, ref missing, ref missing);

                            oWordDoc.Activate();
                        }
                        catch (Exception ex)
                        {
                            Logger.FrameworkLogger.Error("Read file ", ex);
                        }
                        finally
                        {
                            //oWordApp.Visible = true;
                        }
                        object startPosition = 0;
                        object endPosition = (object)oWordDoc.Characters.Count;
                        Range range = oWordDoc.Range(ref startPosition, ref endPosition);
                        string text = range.Text;
                        if (text.Length <= 0)
                            text = "\"Có thể file của bạn đã bị lỗi, xin vui lòng mở file và nhập trực tiếp vào ô văn bản trên màn hình\"";
                        sb.Append(text);
                    }
                }

            }
            catch (Exception ex)
            {
                Logger.FrameworkLogger.Error("Read file ", ex);
            }

            return sb.ToString();

        }



    }
}